<?php

namespace app\commission;

use app\award\Award;
use app\award\Up;
use app\controllers\pay\ForController;
use app\models\group\Group;
use app\models\group\GroupFans;
use app\models\marketing\MarketingGroup;
use app\models\merchant\MerchantPayFor;
use app\models\order\Order;
use app\models\merchant\MerchantOrder;
use app\models\pay\Pay;
use app\models\user\UserAccount;
use app\models\user\UserConsume;
use app\util\Debug;

/**
 * order & merchant paid
 *
 * Class PaidFinish
 * @package app\commission
 */
class PaidFinish
{
    /**
     * wx pay paid
     *
     * @param Pay $pay
     */
    public static function paidRun(Pay $pay)
    {

        $transaction = \Yii::$app->db->beginTransaction();

        try {

            // order
            if ($pay->pay_type == 1) {
                $order = Order::findOne(['sn' => $pay->sn]);
                self::order($order);
            }

            // refill
            if ($pay->pay_type == 2) {
                // Commission::getInstance()->getRefill()->commission($pay);
            }

            // merchant
            if ($pay->pay_type == 3) {
                $order = MerchantOrder::findOne(['sn' => $pay->sn]);
                self::merchant($order);
            }

            $transaction->commit();

        } catch (\Exception $e) {

            $transaction->rollBack();

            Debug::debug('paid-finish-error', $e->getMessage());
        }
    }

    // order paid (order & group)
    public static function order(Order $order)
    {
        // order status
        $order->status = Order::$statusMapping['PAID'];
        $order->save();

        // account
        $account = UserAccount::findOne(['user_id' => $order->user_id]);
        if ($order->use_balance > 0) {

            // 改成锁定的余额了
            // $account->balance -= $order->use_balance;
            $account->lock_balance -= $order->use_balance;
        }
        if ($order->use_score > 0) {
            $account->lock_score -= $order->use_score;
        }
        if ($order->use_platform_ticket > 0) {
            $account->platform_ticket -= $order->use_platform_ticket;
        }
        $account->save();

        // consume
        $consume = new UserConsume();
        $consume->user_id = $order->user_id;
        if ($order->use_balance > 0) {
            $consume->balance = $order->use_balance;
        }
        if ($order->use_score > 0) {
            $consume->score = $order->use_score;
        }
        if ($order->use_platform_ticket > 0) {
            $consume->platform_ticket = $order->use_platform_ticket;
        }
        $consume->order_id = $order->id;
        $consume->status = 1;
        $consume->text = '下单';
        if ($order->is_group == 1) {
            $consume->text = '下单(拼团)';

            $group_id = Group::find()
                ->where(['order_id' => $order->id])
                ->select(['id'])
                ->scalar();
            $consume->group_order_id = $group_id;
        }
        $consume->save();

        // commission or group action
        if ($order->is_group == 1) {
            // action group
            self::group($order);
        } else {
            // commission
            // Commission::getInstance()->getOrder()->commission($order);
        }

        // up level
        // 这里处理了升级和佣金
        // UpLevel::up($order);

        // commission & up
        // new C($order);
        // new C2($order);
        // new U($order);


        // 先升级, 2+1, 那里要判断
        new Award($order);
        new Up($order);

        // stock
        $stock = new Stock($order);
        $stock->run();
    }

    // merchant order paid
    public static function merchant(MerchantOrder $merchantOrder)
    {
        /*
         * 1) change merchant order status
         * 2) create merchant pay for
         * 3) sub account
         * 4) add consume
         */

        $merchantOrder->status = 1;
        $merchantOrder->save();

        $merchant = \app\models\merchant\Merchant::findOne(['id' => $merchantOrder->merchant_id]);

        $amount = $merchantOrder->total * ((100 - $merchant->difference) / 100);

        $pay_for = new MerchantPayFor();
        $pay_for->sn = MerchantPayFor::generateSn();
        $pay_for->user_id = $merchant->user_id;
        $pay_for->pay_sn = $merchantOrder->sn;
        $pay_for->nickname = $merchant->nickname;
        $pay_for->bank_number = $merchant->bank_number;
        $pay_for->amount = $amount;
        $pay_for->status = 0;
        $pay_for->save();

        $account = UserAccount::findOne(['user_id' => $merchantOrder->user_id]);
        $account->ticket -= $merchantOrder->ticket;
        $account->save();

        $consume = new UserConsume();
        $consume->user_id = $merchantOrder->user_id;
        $consume->ticket = $merchantOrder->ticket;
        $consume->merchant_order_id = $merchantOrder->id;
        $consume->status = 1;
        $consume->text = '商家支付';
        $consume->save();

        // call pay for
        ForController::pay(
            $pay_for->sn,
            $pay_for->user_id,
            $pay_for->amount,
            $pay_for->bank_number,
            $pay_for->nickname,
            2,
            '付给商家'
        );
    }

    protected static function group(Order $order)
    {
        // group status
        $group = Group::findOne(['order_id' => $order->id]);
        if ($group) {
            $group->status = 1;
            $group->save();
        }

        // fans status
        $fans = GroupFans::findOne(['order_id' => $order->id]);
        if ($fans) {
            $fans->status = 1;
            $fans->save();
        }

        $params = json_decode($order->request_params);

        // join
        if (isset($params->group_id) && $params->group_id && $params->group_id > 0) {
            self::groupFinish($fans->group_id);
        }

        // random
        if (isset($params->random_group) && $params->random_group) {
            self::groupFinish($fans->group_id);
        }
    }

    protected static function groupFinish($group_id)
    {
        $set = MarketingGroup::getLastOne();
        $max = $set->quantity;

        $fans_count = GroupFans::find()
            ->where(['group_id' => $group_id])
            ->andWhere(['status' => 1])
            ->count();

        if ($fans_count >= $max) {
            $group = Group::findOne(['id' => $group_id]);
            $group->status = 2;
            $group->save();

            Commission::getInstance()->getGroup()->commission($group);
        }

    }
}